//数据库
const loki = require('lokijs');
//路径包
const path = require("path");
const { v4: uuidv4 } = require('uuid');


//获取启动项目录
const rootDir = process.cwd();


//定义储存路径
let fileurl = path.join(rootDir, "lokiFiles/atlasdb.json");

class AtlasDB {
    constructor() {
        this._ready = false;
        this.db = new loki(fileurl, {
            autoload: true,
            autoloadCallback: async () => {
                await this.initCollections();
                this._ready = true;
                if (this._resolveReady) this._resolveReady();
            },
            autosave: true,
            autosaveInterval: 5000
        });
    }

    async initCollections() {
        this.Collection = this.db.getCollection('atlas') ||
            this.db.addCollection('atlas', { unique: ['Atlasname'] });
    }

    //确保数据库初始化完成
    async ready() {
        if (this._ready) return;
        return new Promise(resolve => {
            this._resolveReady = resolve;
        });
    }

    // 添加方法
    async create(savedata) {
        await this.ready();
        if ("Atlasname" in savedata) {
            if (savedata.Atlasname == "") {
                return { success: false, data: "请不要输入空图集名" };
            } else {
                if ("User_id" in savedata) {
                    if (savedata.User_id == "") {
                        return { success: false, data: "请不要输入空用户ID" };
                    } else {
                        //图集名称和用户id都满足了，可以执行保存方法了
                        let data = {
                            User_id: savedata.User_id,
                            Atlasname: savedata.Atlasname,
                            Atlascreatedate: new Date().toISOString(),
                            Atlasimgs: [],
                            Atlas_id: uuidv4()
                        }
                        let findresult = this.Collection.find({ User_id: data.User_id, Atlasname: data.Atlasname })
                        if (findresult.length === 0) {
                            let result = this.Collection.insert(data);
                            return { success: true, data: result }
                        } else {
                            return { success: false, data: "存在该标题" }
                        }
                    }
                } else {
                    return { success: false, data: "请输入用户ID" };
                }
            }
        } else {
            return { success: false, data: "请输入图集名称" };
        }
    }
    // 更新方法
    async update(savedata) {
        await this.ready();
        //检查名称是否存在
        if ("Atlas_id" in savedata) {
            if (savedata.Atlas_id == "") {
                return { success: false, data: "请不要输入空图集名" };
            }
            if ("User_id" in savedata) {
                if (savedata.User_id == "")
                    return { success: false, data: "请不要输入空用户ID" };
                let finddata = {
                    User_id: savedata.User_id,
                    Atlas_id: savedata.Atlas_id
                }
                //查找图集是否存在
                let atlas = this.Collection.findOne(finddata);
                if (atlas) {
                    let atlasimgs = [];
                    for (let i = 0; i < savedata.Atlasimgs.length; i++) {
                        let img = {}
                        if (!savedata.Atlasimgs[i].imgname)
                            return { success: false, data: "图片的名称不存在" }
                        img.imgname = savedata.Atlasimgs[i].imgname;
                        if (!savedata.Atlasimgs[i].imgurl)
                            return { success: false, data: "图片的地址不存在" }
                        img.imgurl = savedata.Atlasimgs[i].imgurl;
                        atlasimgs.push(img);
                    }
                    //赋值更新数据
                    if (savedata.Atlasname)
                        atlas.Atlasname = savedata.Atlasname;
                    if (savedata.Atlasmessage)
                        atlas.Atlasmessage = savedata.Atlasmessage;
                    if (savedata.Atlascovername)
                        atlas.Atlascovername = savedata.Atlascovername;
                    if (savedata.Atlascoverurl)
                        atlas.Atlascoverurl = savedata.Atlascoverurl;
                    if (atlasimgs.length !== 0)
                        atlas.Atlasimgs.push(...atlasimgs)

                    let result = this.Collection.update(atlas);
                    return { success: true, data: result }

                } else {
                    return { success: false, data: "不存在该图集" };
                }
            } else {
                return { success: false, data: "请输入用户ID" };
            }
        } else {
            return { success: false, data: "请传入图集名" };
        }
    }

    // 查找方法
    async find(finddata = {}, limit = 0, sort = "Atlascreatedate") {
        await this.ready();
        if (Object.keys(finddata).length === 0) {
            let result;
            if (limit == 0) {
                result = this.Collection
                    .chain()
                    .find()
                    .simplesort(sort, { desc: true })
                    .data();
            } else {
                result = this.Collection
                    .chain()
                    .find()
                    .simplesort(sort, { desc: true })
                    .limit(limit)
                    .data();
            }
            return { success: true, data: result };
        } else {
            let result;
            if (limit == 0) {
                result = this.Collection
                    .chain()
                    .find(finddata)
                    .simplesort(sort, { desc: true })
                    .data();
            } else {
                result = this.Collection
                    .chain()
                    .find(finddata)
                    .simplesort(sort, { desc: true })
                    .limit(limit)
                    .data();
            }
            return { success: true, data: result };
        }
    }

    // 删除方法
    async delete(finddata = {}) {
        await this.ready();
        if ("User_id" in finddata) {
            if ("Atlas_id" in finddata) {
                let outcome = this.Collection.findOne(finddata);
                if (outcome) {
                    let result = this.Collection.remove(outcome);
                    return { success: true, data: result };
                }
                return { success: false, data: "查找不到数据" };
            } else {
                return { success: false, data: "请输入图集ID" };
            }
        } else {
            return { success: false, data: "请输入用户ID" };
        }
    }

    //删除数组中部分数据
    async deletearray(savedata) {
        await this.ready();
        //检查名称是否存在
        if ("Atlas_id" in savedata) {
            if (savedata.Atlas_id == "") {
                return { success: false, data: "请不要输入空图集名" };
            }
            if ("User_id" in savedata) {
                if (savedata.User_id == "")
                    return { success: false, data: "请不要输入空用户ID" };
                let finddata = {
                    User_id: savedata.User_id,
                    Atlas_id: savedata.Atlas_id
                }
                //查找图集是否存在
                let atlas = this.Collection.findOne(finddata);
                if (atlas) {

                    const namesToRemove = savedata.atlasimgs.map(item => item.imgname);
                    for (let i = atlas.Atlasimgs.length - 1; i >= 0; i--) {
                        if (namesToRemove.includes(atlas.Atlasimgs[i].imgname)) {
                            atlas.Atlasimgs.splice(i, 1); // 从后向前遍历，避免索引错乱
                        }
                    }
                    return { success: true, data: atlas };
                } else {
                    return { success: false, data: "不存在该图集" };
                }
            } else {
                return { success: false, data: "请输入用户ID" };
            }
        } else {
            return { success: false, data: "请传入图集名" };
        }
    }

}

module.exports = new AtlasDB();